<?php
class ModelSaleVoucherTheme extends Model {
	public function addVoucherTheme($data) {
		$this->db->query("INSERT INTO  @@voucher_theme SET image = '" . ES(html_entity_decode($data['image'], ENT_QUOTES, 'UTF-8')) . "'");

		$voucher_theme_id = $this->db->getLastId();

		foreach ($data['voucher_theme_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO  @@voucher_theme_description SET voucher_theme_id = " . $voucher_theme_id . ", language_id = " . (int)$language_id . ", name = '" . ES($value['name']) . "'");
		}
	}

	public function editVoucherTheme($voucher_theme_id, $data) {
		$this->db->query("UPDATE  @@voucher_theme SET image = '" . ES(html_entity_decode($data['image'], ENT_QUOTES, 'UTF-8')) . "' WHERE voucher_theme_id = " . (int)$voucher_theme_id);

		$this->db->query("DELETE FROM  @@voucher_theme_description WHERE voucher_theme_id = " . (int)$voucher_theme_id);

		foreach ($data['voucher_theme_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO  @@voucher_theme_description SET voucher_theme_id = " . (int)$voucher_theme_id . ", language_id = " . (int)$language_id . ", name = '" . ES($value['name']) . "'");
		}
	}

	public function deleteVoucherTheme($voucher_theme_id) {
		$this->db->query("DELETE FROM  @@voucher_theme WHERE voucher_theme_id = " . (int)$voucher_theme_id);
		$this->db->query("DELETE FROM  @@voucher_theme_description WHERE voucher_theme_id = " . (int)$voucher_theme_id);
	}

	public function getVoucherTheme($voucher_theme_id) {
		$query = $this->db->query("SELECT * FROM  @@voucher_theme vt LEFT JOIN  @@voucher_theme_description vtd ON (vt.voucher_theme_id = vtd.voucher_theme_id) WHERE vt.voucher_theme_id = " . (int)$voucher_theme_id . " AND vtd.language_id = " . (int)C('config_language_id'));

		return $query->row;
	}

	public function getVoucherThemes($filter = null) {
		$sql = "SELECT * FROM  @@voucher_theme vt LEFT JOIN  @@voucher_theme_description vtd ON (vt.voucher_theme_id = vtd.voucher_theme_id) WHERE vtd.language_id = " . (int)C('config_language_id');

		if ($filter) {
			$sql .= $filter->sort('vtd.name', 'ASC');
			$sql .= $filter->limit();
		}
		
		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getVoucherThemeDescriptions($voucher_theme_id) {
		$voucher_theme_data = array();

		$query = $this->db->query("SELECT * FROM  @@voucher_theme_description WHERE voucher_theme_id = " . (int)$voucher_theme_id);

		foreach ($query->rows as $result) {
			$voucher_theme_data[$result['language_id']] = array('name' => $result['name']);
		}

		return $voucher_theme_data;
	}

	public function getTotalVoucherThemes() {
      	return $this->db->queryOne("SELECT COUNT(*) AS total FROM  @@voucher_theme");
	}
}
?>